
<template>
  <div>
    <div id="msgShow">
        <div v-for="item in lists" :key="item.id" @click="touser(item.id)">
            {{item.id}}  对  {{item.us}}  说:<br>
            {{item.me}}<br><br>
        </div>
    </div>
    <div id="iconShow">
        <i class="el-icon-picture-outline" style="margin:10px 0 0 5px"></i>
        <i class="el-icon-upload" style="margin:10px 0 0 5px"></i>
        <i class="el-icon-picture" style="margin:10px 0 0 5px"></i>
        <i class="el-icon-upload" style="margin:10px 0 0 5px"></i>
        <el-button @click="websocketsend(sendmsg)" style="float:right">发送消息</el-button> 
        <span style="float:right;padding:10px 5px 0 0">发送对象:{{this.toUser}}</span>
    </div>
    <textarea id="inbox" type="text" v-model="sendmsg" ></textarea><br/>
    
  
    <span id="msgdiv"></span>
  </div>
</template>

<script>
import CostomerServiceApi from "@/api/CostomerService";
export default {
  data() {
      return {
        websock: null,
        message:"",
        sendmsg:"",
        toUser:"",
        lists:[],
        
      }
    },
    created() {
      this.initWebSocket();
    },
    destroyed() {
      this.websock.close() //离开路由之后断开websocket连接
    },
    methods: {
      initWebSocket(){ //初始化weosocket
        const wsuri = "ws://localhost:8090/webSocket/userFont";
        this.websock = new WebSocket(wsuri);
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onclose = this.websocketclose;
      },
      websocketonopen(){ //连接建立之后执行send方法发送数据
        this.websock.send("客服::");
        console.log("连接已建立");
      },
      websocketonerror(){//连接建立失败重连
        this.initWebSocket();
      },
      websocketonmessage(e){ //数据接收
         if(e.data.indexOf("@")>=0){
         var list = e.data.split("@");
         var user={
            id:"",
            me:"",
            us:"你"
        }
         user.id=list[1];
         user.me=list[0];
         this.lists.push(user);
         
         }

      },
      websocketsend(Data){//数据发送
        this.websock.send(this.toUser+"to"+Data);
        var use={
          id:"你",
          me:"",
          us:""
        }
        console.log(this.toUser);
        use.me = this.sendmsg;
        use.us = this.toUser
        this.lists.push(use);
        this.sendmsg="";  
      },
      websocketclose(e){  //关闭
        console.log('断开连接',e);
      },
      touser(id){
        this.toUser = id;
      }
    },
};
</script>

<style>
#msgShow{
    width: 100%;
    height: 450px;
    border: 1px;
    box-shadow: 0 2px 4px rgba(0,0, 0, .12),0 0 6px rgba(0, 0, 0, .04);
    overflow: auto;
}
#inbox{
    width: 100%;
    height: 200px;
    border: 1px;
    box-shadow: 0 2px 4px rgba(0,0, 0, .12),0 0 6px rgba(0, 0, 0, .04);
    resize: none;
    outline: none;
}
#iconShow{
    width: 100%;
    height: 30px;
    padding: 0px 3px 0 3px;
}
</style>